﻿package com.agileai.miscdp.hotweb.generator.pickfill;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;

import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.domain.pickfill.PickFillFuncModel;
import com.agileai.miscdp.hotweb.generator.Generator;
import com.agileai.miscdp.util.MiscdpUtil;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
/**
 * SQLMap文件代码生成器
 */
public class PFMSqlMapGenerator implements Generator{
	private String sqlMapFile = null;
    private String findRecordsSql = null;
    private PickFillFuncModel funcModel = null;
    private String templateDir = null;
    
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void generateFile() {
		try {
			String fileName = "template";
			try {
				templateDir = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource(fileName)).getFile().toString();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Configuration cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(templateDir+"/pickfill"));
	        cfg.setObjectWrapper(new DefaultObjectWrapper());
	        Template temp = cfg.getTemplate("SqlMap.xml.ftl");
	        HashMap tableModel = new HashMap();
	        tableModel.put("namespace", funcModel.getSqlNameSpace());
	        String sql = MiscdpUtil.getProcessedConditionSQL(this.findRecordsSql);
	        tableModel.put("findRecordsSql",sql);
	        Map root = new HashMap();
	        root.put("table",tableModel);
	        FileWriter out = new FileWriter(new File(this.sqlMapFile)); 
	        temp.process(root, out);
	        out.flush();	
	        
		} catch (Exception e) {
			MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(), e);
		}
	}
    
	public void generate() {
		try {
			this.generateFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void setSqlMapFile(String sqlMapFile) {
		this.sqlMapFile = sqlMapFile;
	}
	public void setFindRecordsSql(String findRecordsSql) {
		this.findRecordsSql = findRecordsSql;
	}
	public void setFuncModel(PickFillFuncModel funcModel) {
		this.funcModel = funcModel;
	}
}
